package config

import (
	"log"
	"sync"
	"time"
)

// RedisClient Redis客户端接口
type RedisClient interface {
	Set(key string, value interface{}, expiration time.Duration) error
	Get(key string) (string, error)
	Del(key string) error
	Exists(key string) bool
}

// MockRedisClient 模拟Redis客户端
type MockRedisClient struct {
	data map[string]string
	mu   sync.RWMutex
}

// NewMockRedisClient 创建模拟Redis客户端
func NewMockRedisClient() *MockRedisClient {
	return &MockRedisClient{
		data: make(map[string]string),
	}
}

func (m *MockRedisClient) Set(key string, value interface{}, expiration time.Duration) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	
	// 简单的字符串转换
	var strValue string
	switch v := value.(type) {
	case string:
		strValue = v
	case []byte:
		strValue = string(v)
	default:
		strValue = ""
	}
	
	m.data[key] = strValue
	log.Printf("Mock Redis SET: %s = %s", key, strValue)
	return nil
}

func (m *MockRedisClient) Get(key string) (string, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()
	
	value, exists := m.data[key]
	if !exists {
		return "", nil
	}
	
	log.Printf("Mock Redis GET: %s = %s", key, value)
	return value, nil
}

func (m *MockRedisClient) Del(key string) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	
	delete(m.data, key)
	log.Printf("Mock Redis DEL: %s", key)
	return nil
}

func (m *MockRedisClient) Exists(key string) bool {
	m.mu.RLock()
	defer m.mu.RUnlock()
	
	_, exists := m.data[key]
	log.Printf("Mock Redis EXISTS: %s = %t", key, exists)
	return exists
}

var RedisClientInstance RedisClient

// InitRedis 初始化Redis连接
func InitRedis() {
	if AppConfig.Mock.UseMockRedis || !AppConfig.Redis.Enabled {
		log.Println("使用Mock Redis（开发模式）")
		RedisClientInstance = NewMockRedisClient()
	} else {
		// 这里可以添加真实Redis连接
		log.Println("使用真实Redis连接")
		// TODO: 实现真实Redis连接
		RedisClientInstance = NewMockRedisClient() // 暂时使用Mock
	}
}
